package com.example.ds.aspect;

import com.example.ds.plugins.SlowSqlInterceptor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.stream.Collectors;


@Aspect
@Component
@ConditionalOnProperty(name = "metric.enabled", havingValue = "true")
public class MetricAspect {

    private static final Logger logger = LoggerFactory.getLogger(MetricAspect.class);

    @Around("@annotation(metricTime)")
    public Object metric(ProceedingJoinPoint joinPoint, MetricTime
            metricTime) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String argsStr = Arrays.stream(joinPoint.getArgs()).map(Object::toString)
                .collect(Collectors.joining(","));
        String desc  = metricTime.value();
        long start = System.currentTimeMillis();
        try {
            return joinPoint.proceed();
        } finally {
            long t = System.currentTimeMillis() - start;
            logger.info("[Metrics] 方法调用: {}.{} - 参数: ({}) - 耗时: {} ms - 信息: {}",
                    className, methodName, argsStr, t,  desc);
        }
    }
}
